package com.studyyoun.android.androidcommonbaselibrary.view;

import android.content.Context;
import android.graphics.Color;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.studyyoun.android.androidcommonbaselibrary.R;
import com.studyyoun.android.androidcommonbaselibrary.glide.CommonGlideUtils;

import java.io.Serializable;
import java.util.List;

/**
 * Created by androidlongs on 2018/2/8.
 */

public class LooperTextView extends FrameLayout {
    private List<ItemMsgModel> tipList;
    private int curTipIndex = 0;
    private long lastTimeMillis;
    private static final int ANIM_DELAYED_MILLIONS = 3 * 1000;
    /**
     * 动画持续时长
     */
    private static final int ANIM_DURATION = 1 * 1000;
    private static final String DEFAULT_TEXT_COLOR = "#343434";
    private static final int DEFAULT_TEXT_SIZE = 12;
    private LinearLayout tv_tip_out, tv_tip_in;
    private static final String TIP_PREFIX = " ";
    private Animation anim_out, anim_in;

    public LooperTextView(Context context) {
        super(context);
        initTipFrame();
        initAnimation();
    }

    public LooperTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initTipFrame();
        initAnimation();
    }

    public LooperTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initTipFrame();
        initAnimation();
    }

    private void initTipFrame() {
        tv_tip_out = newLinearLayout(25);
        tv_tip_in = newLinearLayout(25);


        tv_tip_out.addView(newImageView());
        tv_tip_in.addView(newImageView());

        LinearLayout linearLayoutIn = newLinearLayout(10);
        linearLayoutIn.addView(newTextView());

        LinearLayout linearLayoutOut = newLinearLayout(10);
        linearLayoutOut.addView(newTextView());

        tv_tip_out.addView(linearLayoutIn);
        tv_tip_in.addView(linearLayoutOut);


        addView(tv_tip_in);
        addView(tv_tip_out);
    }

    private TextView newTextView() {
        int scaledDensity = (int) getContext().getResources().getDisplayMetrics().scaledDensity;
        TextView textView = new TextView(getContext());
        LayoutParams lp = new LayoutParams(
                LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, Gravity.CENTER_VERTICAL);
        lp.setMargins(10 * scaledDensity, 0, 10 * scaledDensity, 0);
        textView.setLayoutParams(lp);

        textView.setCompoundDrawablePadding(10);
        textView.setGravity(Gravity.CENTER_VERTICAL);
        textView.setLines(2);
        textView.setLineSpacing(1.2f, 1.2f);
        textView.setEllipsize(TextUtils.TruncateAt.END);
        textView.setTextColor(Color.parseColor(DEFAULT_TEXT_COLOR));
        textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, DEFAULT_TEXT_SIZE);
        return textView;
    }

    private ImageView newImageView() {
        int scaledDensity = (int) getContext().getResources().getDisplayMetrics().scaledDensity;
        ImageView imageView = new ImageView(getContext());
        LayoutParams lp = new LayoutParams(scaledDensity * 40, scaledDensity * 40, Gravity.CENTER_VERTICAL);

        imageView.setLayoutParams(lp);
        imageView.setScaleType(ImageView.ScaleType.FIT_XY);
        return imageView;
    }

    private LinearLayout newLinearLayout(int paddinLeft) {
        int scaledDensity = (int) getContext().getResources().getDisplayMetrics().scaledDensity;
        LinearLayout textView = new LinearLayout(getContext());
        LayoutParams lp = new LayoutParams(
                LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, Gravity.CENTER_VERTICAL);
        textView.setLayoutParams(lp);
        textView.setPadding(paddinLeft * scaledDensity, 0, 5 * scaledDensity, 0);
        textView.setOrientation(LinearLayout.HORIZONTAL);
        textView.setGravity(Gravity.CENTER_VERTICAL);

        return textView;
    }

    private void initAnimation() {
        anim_out = newAnimation(0, -1);
        anim_in = newAnimation(1, 0);
        anim_in.setAnimationListener(new Animation.AnimationListener() {

            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                updateTipAndPlayAnimationWithCheck();
            }
        });
    }

    private Animation newAnimation(float fromYValue, float toYValue) {
        Animation anim = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0,
                Animation.RELATIVE_TO_SELF, fromYValue, Animation.RELATIVE_TO_SELF, toYValue);
        anim.setDuration(ANIM_DURATION);
        anim.setStartOffset(ANIM_DELAYED_MILLIONS);
        anim.setInterpolator(new DecelerateInterpolator());
        return anim;
    }

    private void updateTipAndPlayAnimationWithCheck() {
        if (System.currentTimeMillis() - lastTimeMillis < 1000) {
            return;
        }
        lastTimeMillis = System.currentTimeMillis();
        updateTipAndPlayAnimation();
    }

    private void updateTipAndPlayAnimation() {
        if (curTipIndex % 2 == 0) {
            updateTip(tv_tip_out);
            tv_tip_in.startAnimation(anim_out);
            tv_tip_out.startAnimation(anim_in);
            this.bringChildToFront(tv_tip_in);
        } else {
            updateTip(tv_tip_in);
            tv_tip_out.startAnimation(anim_out);
            tv_tip_in.startAnimation(anim_in);
            this.bringChildToFront(tv_tip_out);
        }
    }

    private void updateTip(LinearLayout tipView) {
//        if (new Random().nextBoolean()) {
//            tipView.setCompoundDrawables(head_boy, null, null, null);
//        } else {
//            tipView.setCompoundDrawables(head_girl, null, null, null);
//        }
        String imageUrl = getNextTiImg();
        String tip = getNextTip();
        int scaledDensity = (int) getContext().getResources().getDisplayMetrics().scaledDensity;
        for (int i = 0; i < tipView.getChildCount(); i++) {
            View childAt = tipView.getChildAt(i);
            if (childAt instanceof ImageView) {
                CommonGlideUtils.showImageView(getContext(), R.mipmap.app_icon, imageUrl, ((ImageView) childAt));

            }
            if (childAt instanceof LinearLayout) {
                ((TextView) (((LinearLayout) childAt).getChildAt(0))).setText(tip + TIP_PREFIX);
            }
        }

    }

    /**
     * 获取下一条消息
     *
     * @return
     */
    private String getNextTip() {
        if (isListEmpty(tipList)) return null;
        return tipList.get(curTipIndex % tipList.size()).title;
    }

    private String getNextTiImg() {
        if (isListEmpty(tipList)) return null;
        return tipList.get(curTipIndex++ % tipList.size()).imgUrl;
    }

    public static boolean isListEmpty(List list) {
        return list == null || list.isEmpty();
    }

    public void setTipList(List<ItemMsgModel> tipList) {
        this.tipList = tipList;
        curTipIndex = 0;
        updateTip(tv_tip_out);
        updateTipAndPlayAnimation();
    }

    public static class ItemMsgModel implements Serializable {
        public String title;
        public String imgUrl;
        public String href;

        //打开类型  app  h5
        public String opentype;
        //内容的id，比如医生，诊所，套餐 的id
        public String contentid;
        public String cliniccode;
        //内容类型
        public String contenttype;
    }

    public int getCurTipIndex() {
        return curTipIndex;
    }
}